#include "game_http.h"
#include "game_log.h"
#include "game_ev.h"
#include <unistd.h>
#include "game_version.h"
#include <string.h>

using namespace CGame::Httpd;

// void __log(const char * format, ...){
//   va_list args;
//   va_start(args,format);

//   vfprintf(stdout,format,args);

//   va_end(args);
// }


class CCHttpd:public CGameHttpd{
private:
  void onIndex(Request *req);
public:
  CCHttpd(const char* root);
  void run();
  BOOL init(int port);
};

CCHttpd::CCHttpd(const char* root):CGameHttpd(root){
};

void CCHttpd::run(){
  CGameHttpd::run();
  do{

    usleep(_sleep *1000);
  }while(true);
}

void CCHttpd::onIndex(Request *req){
  // const char *iii = req->getParameter("i");
  // const char *jjj = req->getParameter("j");
  // if(NULL != iii){
  //   __log("p is %s",iii);
  // }
  // _response->html(req,"Response By IndezHandler.");

  if(0 == strcmp("/",req->getRequestURL())){
    _response->redirect(req,"/index");
    return;
  }

  const char *u2 = req->getCookie("u2");
  __log("u2 is %s\n",u2);

  // _response->header(req,"Set-Cookie","_u1=1234356");
  // _response->header(req,"Set-Cookie","_u2=123356;path=/");
  _response->cookie(req,"u1","12345678");
  _response->cookie(req,"u2","888888",60 * 60 * 24);
  _response->html(req,"index123");
}



BOOL CCHttpd::init(int port){

  get("/",Handler(this,&CCHttpd::onIndex));
  get("/index",Handler(this,&CCHttpd::onIndex));
  return CGameHttpd::init(port);
}



int main()
{
  __vprint();
  __ev_config();
  CCHttpd httpd{"/mnt/d/images"};
  if(httpd.init(8080))
    httpd.run();
}
